package com.myj.jim.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myj.jim.domain.FileTransfer;
import com.myj.jim.domain.Operator;
import com.myj.jim.domain.ResultMessage;
import com.myj.jim.domain.bootstraptable.BootstrapTable;
import com.myj.jim.domain.bootstraptable.BootstrapTableJSON;
import com.myj.jim.service.FileTransferService;
import com.myj.jim.util.BootstrapTableUtil;
import com.myj.jim.util.FileManage;
import com.myj.jim.util.JimUtil;

@Controller
@RequestMapping("/fileTransfer")
public class FileTransferController {
	
	private static final String PAGE_AUTHORITY = "fileTransferManage";
	
	private static final String NO_AUTHORITY_VIEW = "common/noAuthorityPage";
	
	@Autowired
	private FileTransferService fileTransferService;
	
	@RequestMapping("/page")
	public String page(HttpServletRequest req, HttpSession session){
		String path = req.getContextPath();
		String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/";
		Operator op = (Operator)session.getAttribute("operator");
		if(op!=null){
			if(JimUtil.haveAuthority(op, PAGE_AUTHORITY)){
				return "fileTransfer/page";
			}else{
				return NO_AUTHORITY_VIEW;
			}
			
		}else{
			//到登录页面
			return "redirect:"+basePath+"index.jsp";
		}
	}
	
	@RequestMapping("/list")
	@ResponseBody
	public BootstrapTableJSON<FileTransfer> list(BootstrapTable bt){
		Map<String,Object> map = BootstrapTableUtil.getParamMap(bt);
		return fileTransferService.findPage(map);
	}
	
	@RequestMapping("/save")
	public String save(HttpServletRequest req, FileTransfer ft){
		String path = FileManage.upLoadFile(req);
		if(StringUtils.isNotBlank(path)){
			ft.setFilepath(path);
			fileTransferService.save(ft);
		}
		return "redirect:page";
	}
	
	@RequestMapping("/download")
	public void download(HttpServletRequest req, HttpServletResponse resp){
		FileManage.downLoad(req, resp);
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public ResultMessage delete(Integer id,String filepath){
		ResultMessage rm = new ResultMessage();
		
		if(fileTransferService.delete(id)){
			if(StringUtils.isNotBlank(filepath)){
				FileManage.delFile(filepath);
			}
			rm.setMessage("删除成功");
			rm.setSuccess(true);
		}else{
			rm.setMessage("删除失败");
			rm.setSuccess(false);
		}
		return rm;
	}
	
	@RequestMapping("/update")
	public String update(FileTransfer ft){
		
		fileTransferService.update(ft);
		return "redirect:page";
	}
}
